package com.ThreadSyncEg;

//售票系统
//锁 同步方法
public class TicketEg implements Runnable{
    //票数
    private int ticket =40;
    boolean flag = true;
    @Override
    public void run() {
        while (flag){
            buy();
            try{
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TicketEg testThread3 = new TicketEg();
        //对象代理开启线程
        Thread t1 = new Thread(testThread3, "A");
        t1.start();
        Thread t2 =new Thread(testThread3,"B");
        t2.start();
        Thread t3 =new Thread(testThread3,"C");
        t3.start();
//        new Thread(()-> System.out.println("123")).start();

        Thread.State state1 = t1.getState();
        Thread.State state2 = t2.getState();
        Thread.State state3 = t3.getState();
        while (state1!=Thread.State.TERMINATED||state2!=Thread.State.TERMINATED||state3!=Thread.State.TERMINATED){
            Thread.sleep(100);
            state1 = t1.getState();
            state2 = t2.getState();
            state3 = t3.getState();
            System.out.println("t1运行状态："+state1+"|t2运行状态："+state2+"|t3运行状态："+state3);
        }

    }
    //锁方法  一次只能有一个线程进入该方法 当前线程执行完后别的线程才能进入
    private synchronized void buy(){
//        synchronized (this){ //this 当前对象 即buy()方法
            if (ticket<=0){
                flag=false;
            }
            if(ticket>=0){
                System.out.println(Thread.currentThread().getName()+"拿到票号："+ ticket--);
            }

//        }
    }
}
